import { createContext, useContext, useRef } from 'react';
import stores from '@/stores';
import * as services from '@/services';
import { debounce } from 'lodash';

const storeContext = createContext(stores);
const serviceContext = createContext(services);

/**
 * 返回rootStore
 * 示例:
 * ```js
 * const { loginStore } = useStore();
 * ```
 *
 * @returns rootStore
 */
export function useStore() {
  return useContext(storeContext);
}

/**
 * 组件上下文中使用服务时，可通过这个hook
 * @returns
 */
export function useService() {
  return useContext(serviceContext);
}

/**
 * 用于键盘输入时的防抖请求. 示例：
 * ```
 * const debounceFetch = useDebounce((args) => {
 *   // 【注意】useDebounce内部不可以引用任何state，所需数据通过参数传递
 *   fetchData(args);
 * });
 *
 * useEffect(() => () => debounceFetch.cancel(), [debounceFetch]); // 清理句柄
 *
 * const keywordChange = (keyword) => {
 *   setKeyword(keyword); // 及时触发UI重绘
 *   debounceFetch({ keyword }); // 执行防抖操作
 * };
 * ```
 * @param {function} callback  回调函数
 * @returns
 */
export const useDebounce = (callback) => {
  return useRef(debounce(callback, 200, { leading: false, trailing: true })).current;
};
